package com.kinon.gfcanteen_v1.util;



import android.util.Log;

import com.kinon.gfcanteen_v1.bean.BaseBean;
import com.kinon.gfcanteen_v1.network.ApiException;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableEmitter;
import io.reactivex.FlowableOnSubscribe;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;



/**
 * Created by lhqq on 2017-12-19.
 */

public class RxUtil {


    /**
     * 统一线程处理
     * @param <T>
     * @return
     */

    public static <T> FlowableTransformer<T,T> rxSchedulerHelper(){
        return new FlowableTransformer<T, T>() {
            @Override
            public Flowable<T> apply(Flowable<T> observable) {
                return observable.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }


    public static <T> FlowableTransformer<BaseBean<T>, T> handleResult() {   //compose判断结果
        return new FlowableTransformer<BaseBean<T>, T>() {
            @Override
            public Flowable<T> apply(Flowable<BaseBean<T>> httpResponseFlowable) {
                return httpResponseFlowable.flatMap(new Function<BaseBean<T>, Flowable<T>>() {
                    @Override
                    public Flowable<T> apply(BaseBean<T> tHttpResponse) {
                        Log.e("lh", "code== "+tHttpResponse.isCode() );
                        if(tHttpResponse.isCode()) {
                            return createData(tHttpResponse.getData());
                        } else {
                            return Flowable.error(new ApiException(tHttpResponse.getMsg()));
                        }
                    }
                });
            }
        };
    }

    /**
     * 生成Flowble
     * @param t
     * @param <T>
     * @return
     */
    public static <T> Flowable<T> createData(final T t) {
        return Flowable.create(new FlowableOnSubscribe<T>() {
            @Override
            public void subscribe(FlowableEmitter<T> emitter) throws Exception {
                try {
                    emitter.onNext(t);
                    emitter.onComplete();
                } catch (Exception e) {
                    emitter.onError(e);
                }
            }
        }, BackpressureStrategy.BUFFER);
    }

}
